import rsaSign from "../../common/rsa.js";
import CryptoJS from "../../common/CryptoJS.js";
import appconf from "../../common/appconf.js";
const domain = appconf.domain;

"use strict";
export default {
    data() {
        return {
			userId:'',
			indicatorDots: true,
			autoplay: true,
			interval: 2000,
            imgUrls: [], // banner图
            isFirstLoad: true, // 是否第一次加载
            goodsList: [], // 商品列表
            contentList: [{
                typeName: '全部',
                type: '',
                list: []
            }], // 商品列表(新)
            classyIndex: 0, // 分类索引
            pages: 1, // 当前页码
            pageSize: 1000, // 每页条目数量
            noMore: false, // ，没有更多数据了
            version: "", // app引擎版本号.支付宝要求版本号:10.0.18  微信要求版本号:2.6.0
            state: this.$store.state,
            errCount: 0,
            needUserConfirm: appconf.wx.need_user_confirm,
            isOpening: false, // 用户正点击开门按钮尝试开门
            banner: [], // 优惠券
            bannerPhoto: [],
            domain: appconf.domain,
            newDomain: ''
        }
    },
    onLoad(options) {
        console.log("index.onLoad, options:", options);
        const onLogin = () => {

            this.$util.extractParams(this, options);
            //this.getPageData(); //加载商品列表数据
            this.whichRole();
            this.getActivity();
            this.getBanners();

            this.getServerStatus();

            if (this.$store.state.userInfo.userId) {
                this.whichRole();
                // #ifdef MP-WEIXIN
                if (!appconf.wx.need_user_confirm) { // 不启用支付分用户确认模式
                    this.queryPayScroreStatus(); // 查询是否开通支付分
                }
                // #endif	
                // #ifdef MP-ALIPAY
                // this.queryAliSilencePayStatus(); // 查询是否开通支付宝免密支付
                // #endif
            }
        };

        this.$util.checkLogin(this, onLogin);
    },
    onShow() {
		this.userId=uni.getSystemInfoSync('userId')
        if (!this.isFirstLoad) {
            return;
        }

        this.isFirstLoad = false;
    },

    /*监听底部上拉事件*/
    onReachBottom() {
        // 由于项目需求，现在暂不使用分页
        // if (this.noMore == false) {
        // 	this.pages++;
        // 	this.getPageData();
        // }
    },
    methods: {
		JumpMyCoupon(){
			uni.navigateTo({
			    url: "/pages/mine/coupon/coupon"
			})
		},
		LoginJump() {
		    uni.navigateTo({
		        url: "/subpackages/login/login"
		    })
		},
        activeJump() {
            uni.navigateTo({
                url: "/pages/index/active/active"
            })
        },
        // 获取活动信息 
        getActivity() {
            let data = {
                pageSize: this.pageSize,
                pageNo: this.pages
            }
            this.$request(this.$api.Coupons, data, "GET").then(res => {
                if (res.code == 200) {
                    this.banner = res.result.records.map(item => {
                        return {
                            banner: item.banner,
                            statusName: item.statusName
                        }
                    })
                }
            })
        },
        // 拼接图片路径
        getBanner(photo) {
            if (this.domain === 'https://api.example.com/') {
                this.newDomain = "https://media.example.com//"
            } else if (this.domain === 'https://api.dev.example.com/') {
                this.newDomain = "https://api.dev.example.com//tcstore/"
            }
            return (this.newDomain + photo)
            // console.log("图片路径",this.newDomain + photo)
            console.log("图片路径", this.newDomain + photo)
        },

        // 开启订阅消息
        openMsg() {
            let that = this
            // 获取用户的当前设置，判断是否点击了“总是保持以上，不在询问”
            wx.getSetting({
                withSubscriptions: true, //是否获取用户订阅消息的订阅状态，默认false不返回
                success(res) {
                    console.log(res)
                    if (res.authSetting['scope.subscribeMessage']) { //用户点击了“总是保持以上，不再询问”
                        uni.openSetting({ // 打开设置页
                            success(res) {
                                console.log(res.authSetting)
                            }
                        });
                    } else { // 用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息
                        let templateid = [
                            'jFBgTV5atfDDz2wSSpxzLglRGIPL75tuXsk0iHRbqiU',
                            'xVvYnFKgTiaDbWPOb2wQ95AbuhrNL2RJA9UbheOZr6s',
                            '6GCyt4Tu3Bqv5D9IQkSwMMR0vWsLC9McGj6vy42aPfc'
                        ]
                        uni.requestSubscribeMessage({
                            tmplIds: templateid,
                            success(res) {
                                let successTempid = []
                                for (let i in res) {
                                    if (res[i] == "accept") successTempid.push(i)
                                }
                                const data = {
                                    openId: that.$store.state.userInfo.openId,
                                    userId: that.$store.state.userInfo.userId,
                                    templateIdListStr: successTempid.toString(),
                                }
                                console.log(data)
                                that.$request(that.$api.Subscribe, data, "post").then(res => {
                                    if (res.code == 200) {
                                        uni.showToast({
                                            title: '提交成功',
                                            duration: 2000,
                                            icon: 'none'
                                        })
                                    } else {
                                        uni.showToast({
                                            title: '提交失败',
                                            icon: "none"
                                        });
                                    }
                                })
                            },
                            fail: (res) => {
                                console.log(res)
                            }
                        })
                    }
                }
            })
        },
        getBanners() {
            this.$request(this.$api.getBanners, {
                deviceId: this.$store.state.deviceId
            }).then(res => {
                if (res.code == 200) {

                    this.imgUrls = res.result
                }
            })
        },
        // 根据角色分配操作
        whichRole: function() { // 设置角色，消费者或上货员
            this.isManage(); // 查询是否为上货员
            return false;
            // if (this.$store.state.role == 1) { // 消费者
            // 	this.isNotRegister();
            // } else if (this.$store.state.role == 2) { // 上货员
            // 	uni.showModal({
            // 		title: '提示',
            // 		content: '您的身份是上货员，请问需要进入上货员页面吗？',
            // 		showCancel: true,
            // 		cancelText: '取消',
            // 		confirmText: '进入',
            // 		success: res => {
            // 			if (res.confirm) {
            // 				uni.redirectTo({
            // 					url: '/pages/indexManage/indexManage',
            // 				});
            // 			} else {
            // 				this.$store.state.role = 1; // 改为消费者身份
            // 				this.whichRole();
            // 			}
            // 		},
            // 	});

            // }
        },

        // 查询系统服务开启状态
        getServerStatus: function() {
            this.$request(this.$api.GetServerStatus).then(res => {
                if (res.returnCode == 'SUCCESS') {
                    this.$store.state.serverStatus = res.data.open || false;
                    if (!this.$store.state.serverStatus) {
                        uni.showModal({
                            title: '提示',
                            content: '系统维护中,请稍后使用',
                            showCancel: false,
                        });
                    }
                }
            })
        },

        // 获取设备信息（查询版本号）
        getVersion: function() {
            uni.getSystemInfo({
                success: (res) => {
                    console.log("版本" + res.version);
                    this.version = res.version;
                    // #ifdef MP-WEIXIN
                    let requireVersion = "10.0.18".split(".");
                    let tips = "您的微信版本过低，请升级再使用";
                    // #endif
                    // #ifdef MP-ALIPAY
                    let requireVersion = "2.6.0".split(".");
                    let tips = "您的支付宝版本过低，请升级再使用";
                    // #endif

                    this.version.split(".").forEach((item, index) => {
                        if (requireVersion[index] < item) {
                            uni.showModal({
                                title: '提示',
                                content: tips,
                                showCancel: false,
                            });
                            return false;
                        }
                    })
                }
            });
        },

        // 查询是否开通支付分
        queryPayScroreStatus: function() {
            let data = {
                openid: this.$store.state.userInfo.openId,
            }
            this.$request(this.$api.QueryPayScoreStatus, data).then(res => {
                if (res.returnCode == "FAIL") { // 未开通
                    uni.showModal({
                        title: "开通微信支付分服务",
                        content: "需要您开通支付分后享受本产品，是否继续开通？",
                        confirmText: "前往开通",
                        cancelText: "我再想想",
                        success: (res) => {
                            if (res.confirm) {
                                this.payScoreAgree(); // 调起开通微信支付分（免密支付）
                            }
                        }
                    })
                }
            })
        },

        // 查询支付宝免密支付开通状态
        queryAliSilencePayStatus: function() {
            let data = {
                aliUserId: this.$store.state.userInfo.aliUserId,
            }
            this.$request(this.$api.QueryAliSilencePayStatus, data).then(res => {
                if (res.returnCode == "FAIL") { // 未开通
                    uni.showModal({
                        title: "开通免密支付",
                        content: "需要您开通免密支付后享受本产品，是否继续开通？",
                        confirmText: "前往开通",
                        cancelText: "我再想想",
                        success: (res) => {
                            if (res.confirm) {
                                this.openingNoSecretPay(); // 调起开通支付宝免密支付
                            }
                        }
                    })
                }
            })
        },

        // 获取页面数据
        getPageData: function() {
            const that = this;
            console.log("index.getPageData, deviceId:" + this.$store.state.deviceId);
            // if(this.$store.state.userInfo.userId == undefined){
            // 	setTimeout(function(){
            // 		that.errCount++
            // 		console.log('a')
            // 		that.getPageData()
            // 	}, 1000);
            // }

            if (!this.$store.state.deviceId) { // 无设备id时
                // 无设备id时
                // uni.showModal({
                // 	title: '提示',
                // 	content: '请扫描设备上的二维码,否则将无法使用',
                // 	showCancel: false,
                // 	confirmText: '扫码',
                // 	success: res => {
                // 		if(res.confirm){
                // 			this.scanToGetData();
                // 		}
                // 	}
                // });
                return;
            }

            let data = {};
            let url = "";
            data.deviceId = this.$store.state.deviceId; // 设备id
            data.pageNo = this.pages; // 页码
            data.pageSize = this.pageSize; // 长度
            url = this.$api.GetGoodsListByDevice;
            this.$util.request(url, data, "GET").then(res => {
                if (res.code == 200) {
                    // console.log(res.result)
                    res.data = res.result.records || [];
                    let contentList = this.contentList;
                    let hasType = ['全部'];
                    if (res.data.length) {
                        res.data.forEach((item, i) => {
                            item.price = Number(item.price).toFixed(2)
                            contentList[0].list.push(item);
                            let index = hasType.indexOf(item.typeName);
                            if (index != -1) {
                                contentList[index].list.push(item);
                            } else {
                                hasType.push(item.typeName);
                                contentList.push({
                                    typeName: item.typeName,
                                    type: item.type,
                                    list: []
                                })
                                contentList[hasType.indexOf(item.typeName)].list.push(item);
                            }
                        })
                    }
                    this.contentList = contentList;
                    if (res.data.length < this.pageSize) {
                        this.noMore = true;
                    }
                } else {
                    uni.showToast({
                        title: res.returnMessage,
                        icon: "none"
                    });
                }
            });
        },
        // 扫码获取数据
        scanToGetData: function() {
            uni.scanCode({
                onlyFromCamera: false,
                success: (res) => {
                    this.$util.extractUri(this, res.result)
                    console.log('扫码')
                    const onLogin = () => {
                        //this.getPageData();
                        this.isManage();
                        this.getBanners()
                    }
                    this.$util.checkLogin(this, onLogin);
                },
                complete: (res) => {
                    console.log(res)
                }
            });
        },

        // 调起授权支付分(微信)
        payScoreAgree: function() {
            if (!this.$store.state.serverStatus) {
                uni.showModal({
                    title: '提示',
                    content: '系统维护中,请稍后使用',
                    showCancel: false,
                });
                return false;
            }
            let that = this;
            let out_request_no = this.$util.radomString(20).toUpperCase(); // 侧单号
            let nonce_str = this.$util.radomString(30); // 随机字符串
            let timestamp = ""; // 当前时间戳（秒）
            let sign_type = "HMAC-SHA256"; // 签名方式
            let sign = ""; // 签名（生成的签名）
            let myDate = new Date(); // 实例化时间对象
            timestamp = parseInt(myDate.getTime() / 1000).toString(); // 获取时间戳
            let tempString = "mch_id=" + appconf.wx.mch_id + "&nonce_str=" + nonce_str + "&out_request_no=" +
                out_request_no +
                "&service_id=" + appconf.wx.service_id + "&sign_type=" + sign_type + "&timestamp=" + timestamp +
                "&key=" + appconf.wx.api_key;
            sign = CryptoJS.HmacSHA256(tempString, appconf.wx.api_key).toString().toUpperCase();

            let data = {
                mch_id: appconf.wx.mch_id,
                service_id: appconf.wx.service_id,
                out_request_no: out_request_no,
                timestamp: timestamp,
                nonce_str: nonce_str,
                sign_type: sign_type,
                sign: sign
            }
            console.log("这里")
            if (uni.openBusinessView) {
                uni.openBusinessView({
                    businessType: 'wxpayScoreEnable',
                    extraData: data,
                    success(res) {},
                    fail(res) {},
                    complete(res) {
                        that.queryPayScroreStatus()
                    }
                });
            } else {
                //引导用户升级微信版本
                uni.showModal({
                    title: '提示',
                    content: "您的微信版本过低，请升级再使用",
                    showCancel: false,
                });
            }
        },

        cancelWxpayOrder: function(orderId) {
            let data = {
                userId: 'quxiao',
                orderId: orderId
            }
            this.$request(this.$api.CancelOrder, data, "GET", false).then(res => {
                console.log(res)
                if (res.returnCode == 'SUCCESS') {
                    console.log('开门失败，支付分订单已取消');
                } else {
                    uni.showModal({
                        title: '取消支付分订单失败，请联系客服处理',
                        content: res.message,
                        showCancel: false,
                    });
                }
            })
        },

        // 调起代扣授权（支付宝）
        openingNoSecretPay: function() {
            let signStr = "";
            // 公共参数
            let biz_content = {}; // 请求参数的集合(除公共参数外的其他参数)
            let method = "alipay.user.agreement.page.sign"; // 接口名称
            let sign_type = "RSA2"; // 商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            let timestamp = this.$util.formatTime(new Date().getTime()); // 示例：2014-07-24 03:07:50
            let version = "1.0"; // 调用的接口版本，固定为：1.0
            let sign = ""; // 签名
            // 请求参数
            let access_params = {};
            let channel =
                "ALIPAYAPP"; // 签约通道方式。目前支持以下值：1. ALIPAYAPP （钱包h5页面签约）2. QRCODE(扫码签约)3. QRCODEORSMS(扫码签约或者短信签约)
            let personal_product_code = "GENERAL_WITHHOLDING_P"; // 个人签约产品码，商户和支付宝签约时确定，商户可咨询技术支持。
            access_params.channel = channel;
            biz_content.access_params = access_params;
            biz_content.personal_product_code = personal_product_code;
            signStr = "app_id=" + appconf.alipay.app_id + "&biz_content=" + JSON.stringify(biz_content) +
                "&charset=" + appconf.alipay.charset + "&method=" +
                method + "&sign_type=" + sign_type + "&timestamp=" + timestamp + "&version=" + version;
            // 方式1: 先建立 key 对象, 构建 signature 实例, 传入 key 初始化 -> 签名
            let key = rsaSign.KEYUTIL.getKey(appconf.alipay.privateKey);
            // 创建 Signature 对象
            let signature = new rsaSign.KJUR.crypto.Signature({
                alg: "SHA256withRSA"
            });
            // 传入key实例, 初始化signature实例
            signature.init(key);
            // 传入待签明文
            signature.updateString(signStr);
            // 签名, 得到16进制字符结果
            let a = signature.sign();
            sign = rsaSign.hextob64(a);
            signStr = "app_id=" + encodeURIComponent(appconf.alipay.app_id) + "&biz_content=" + encodeURIComponent(
                    JSON.stringify(biz_content)) + "&charset=" + encodeURIComponent(appconf.alipay.charset) +
                "&method=" +
                encodeURIComponent(method) + "&sign=" + encodeURIComponent(sign) + "&sign_type=" +
                encodeURIComponent(sign_type) + "&timestamp=" + encodeURIComponent(timestamp) + "&version=" +
                encodeURIComponent(version);
            signStr = encodeURIComponent(signStr)
            uni.paySignCenter({
                signStr: signStr,
                success: (res) => {},
                fail: (res) => {},
                complete: (res) => {
                    this.queryAliSilencePayStatus();
                }
            });
        },

        // 点击我的
        mine: function() {
            uni.navigateTo({
                url: "/pages/mine/mine"
            })
        },
		IndexJump(){
			uni.navigateTo({
			    url: "/pages/index/index"
			})
		},
			
		orderJump(){
			uni.navigateTo({
			    url: "/pages/mine/order/order"
			})
		},
        // 报修
        fault: function() {
            if (this.$store.state.deviceId) {
                uni.navigateTo({
                    url: "/pages/fault/fault"
                })
                return;
            }
            uni.showModal({
                title: '提示',
                content: '请扫描设备上的二维码，以便我们知道您身边的设备',
                showCancel: true,
                cancelText: '取消',
                confirmText: '扫码',
                success: res => {
                    if (!res.confirm) {
                        return;
                    }
                    uni.scanCode({
                        onlyFromCamera: false,
                        success: (res) => {
                            this.$util.extractUri(this, res.result)
                            //this.getPageData();
                            this.fault();
                            this.isManage();
                        },
                        complete: (res) => {
                            console.log(res)
                        }
                    });
                }
            });
        },
        // 开门前判断是否满足开门条件
        openCondition: function() {
            if (!this.$store.state.serverStatus) {
                uni.showModal({
                    title: '提示',
                    content: '系统维护中,请稍后使用',
                    showCancel: false,
                });
                return false;
            }

            if (this.$store.state.userInfo.status && this.$store.state.userInfo.status != 0) {
                uni.showModal({
                    title: '提示',
                    content: '您的账号已被禁用或注销。具体原因，请与我们的客服人员联系：' + this.$store.state.userInfo.customerTel,
                    showCancel: false,
                });
                return false;
            }

            if (!this.$store.state.deviceId) {
                uni.showModal({
                    title: '提示',
                    content: '请扫码设备上的二维码，以便知道您身边的设备',
                    showCancel: true,
                    confirmText: '扫码',
                    success: res => {
                        if (res.confirm) {
                            this.startScanCode(); // 开启扫码
                        }
                    },
                });
                return false;
            }
            // #ifdef MP-ALIPAY
            this.getDeviceStatus();
            // #endif
            // #ifdef MP-WEIXIN
            let data = {}
            data.openid = this.$store.state.userInfo.openId; // 微信用户与微信小程序的唯一标识
            if (appconf.wx.need_user_confirm) { // 启用支付分用户确认模式
                this.getDeviceStatus();
            } else {
                // 不启用支付分用户确认模式
                this.$request(this.$api.QueryPayScoreStatus, data).then(res => {
                    if (res.returnCode == "SUCCESS") { // 满足支付分条件
                        this.getDeviceStatus();
                    } else {
                        this.payScoreAgree(); // 开通微信支付分
                    }
                })
            }
            // #endif
        },

        // 查询设备状态（状态正常才允许调用开门）
        getDeviceStatus: function() {
            let data = {
                deviceId: this.$store.state.deviceId,
            }
            this.$request(this.$api.QueryDeviceStatus, data).then(res => {
                if (res.returnCode == "SUCCESS") {
                    switch (Number(res.data.deviceStatus)) {
                        case 1: // 正常
                            switch (Number(res.data.status)) {
                                case 1: // 已经开门
                                    uni.showModal({
                                        title: '提示',
                                        content: '设备开门状态',
                                        showCancel: false,
                                    });
                                    break;
                                case 2: // 关门状态
                                    // #ifdef MP-WEIXIN
                                    this.open(); // 去开门
                                    // #endif
                                    // #ifdef MP-ALIPAY
                                    this.queryAlipaySingleSignStatus(); // 查询开通状态（单次授权签约）
                                    // #endif
                                    break;
                                case 3: // 无法获取设备状态
                                    uni.showModal({
                                        title: '提示',
                                        content: '未获取到设备信息',
                                        showCancel: false,
                                    });
                                    break;
                                case 4: // 异常
                                    uni.showModal({
                                        title: '提示',
                                        content: '设备状态异常',
                                        showCancel: false,
                                    });
                            }
                            break;
                        case 2: // 冻结
                            uni.showModal({
                                title: '提示',
                                content: '设备冻结中',
                                showCancel: false,
                            });
                            break;
                        case 3: // 学习
                            uni.showModal({
                                title: '提示',
                                content: '设备学习中',
                                showCancel: false,
                            });
                            break;
                        case 4: // 异常
                            uni.showModal({
                                title: '提示',
                                content: '设备异常中',
                                showCancel: false,
                            });
                    }
                } else {
                    uni.showModal({
                        title: '提示',
                        content: res.returnMessage,
                        showCancel: false,
                    });
                }
            })
        },

        // 支付宝单次授权
        alipaySingleSign: function() {
            let deviceId = this.$store.state.deviceId;
            this.$request(this.$api.GetAlipaySingleSign + '?deviceId=' + deviceId).then(res => {
                if (res.returnCode == "SUCCESS") {
                    let signUrl = res.data.split(":")[1].replace(/"/g, '');
                    uni.paySignCenter({
                        signStr: signUrl,
                        success: (res) => {
                            console.log(res)
                            this.queryAlipaySingleSignStatus(); // 查询开通状态
                        }
                    });
                } else {
                    uni.showToast({
                        title: '获取签约签名失败',
                        icon: 'none'
                    });
                }
            })
        },

        // 支付宝单次授权解约
        unSingleSign: function() {
            let aliUserId = this.$store.state.userInfo.aliUserId;
            this.$request(this.$api.UnSingleSign + '?aliUserId=' + aliUserId).then(res => {
                if (res.returnCode == "SUCCESS") {

                } else {

                }
            })
        },

        // 查询单次支付宝签约状态（已授权可直接开门）
        queryAlipaySingleSignStatus: function() {
            let aliUserId = this.$store.state.userInfo.aliUserId;
            this.$request(this.$api.QueryAliSingleSignStatus + '?aliUserId=' + aliUserId).then(res => {
                if (res.returnCode == "SUCCESS") {
                    this.open(); // 已授权签约，直接开门
                } else {
                    uni.showModal({
                        title: '支付协议签约授权',
                        content: '开门需签订支付协议，订单结束后将自动解约',
                        showCancel: true,
                        cancelText: '取消',
                        confirmText: '确认签约',
                        success: res => {
                            console.log(res)
                            if (res.confirm) {
                                this.alipaySingleSign(); // 未授权签约则调起签约
                            }
                        }
                    });
                }
            })
        },
        
        openConfirmPayScore: function(orderId, orderPackage) {
            if (!this.$store.state.serverStatus) {
                uni.showModal({
                    title: '提示',
                    content: '系统维护中,请稍后使用',
                    showCancel: false,
                });
                return false;
            }
        
            let out_request_no = this.$util.radomString(20).toUpperCase(); // 侧单号
            let nonce_str = this.$util.radomString(30); // 随机字符串
            let timestamp = ""; // 当前时间戳（秒）
            let sign_type = "HMAC-SHA256"; // 签名方式
            let sign = ""; // 签名（生成的签名）
            let myDate = new Date(); // 实例化时间对象
            timestamp = parseInt(myDate.getTime() / 1000).toString(); // 获取时间戳
            let tempString = "mch_id=" + appconf.wx.mch_id + "&nonce_str=" + nonce_str + "&out_request_no=" +
                out_request_no +
                "&service_id=" + appconf.wx.service_id + "&sign_type=" + sign_type + "&timestamp=" + timestamp +
                "&key=" + appconf.wx.api_key;
            sign = CryptoJS.HmacSHA256(tempString, appconf.wx.api_key).toString().toUpperCase();
        
            let data = {
                mch_id: appconf.wx.mch_id,
                package: orderPackage,
                timestamp: timestamp,
                nonce_str: nonce_str,
                sign_type: sign_type,
                sign: sign
            }
            console.log("openConfirmPayScore")
            if (uni.openBusinessView) {
                uni.openBusinessView({
                    businessType: 'wxpayScoreUse',
                    extraData: data,
                    success: res => {
                        console.log("openBusinessView success");
                        console.log(res);
                        if (res.extraData.query_id != undefined) {
                            uni.navigateTo({
                                url: "/pages/index/successOpen/successOpen?orderId="+orderId
                            });
                        } else {
                            // this.cancelWxpayOrder(orderId);
                            uni.showToast({
                                title: '开门失败，请先授权微信支付分再尝试',
                                icon: 'none'
                            });
                        }
                    },
                    fail: res => {
                        console.log("openBusinessView fail");
                        console.log(res);
                        // this.cancelWxpayOrder(orderId);
                        uni.showToast({
                            title: '开门失败，请先授权微信支付分再尝试',
                            icon: 'none'
                        });
                    },
                    complete: res => {
                        console.log("complete");
                    }
                });
            } else {
                //引导用户升级微信版本
                uni.showModal({
                    title: '提示',
                    content: "您的微信版本过低，请升级再使用",
                    showCancel: false,
                });
            }
        },


        // 请求开门
        open: function() {
            if (this.isOpening) {
                console.log('正在开门中，请勿重复申请开门');
                return;
            }

            let data = {
                deviceId: this.$store.state.deviceId,
                openType: 1, // 消费开门请求
            }

            let doorIndex = this.$store.state.doorIndex;
            if (typeof(doorIndex) != 'undefined' && doorIndex != null) {
                data.doorIndex = doorIndex
            }

            this.isOpening = true;
            setTimeout(() => {
                this.isOpening = false;
            }, 5000);

            this.$request(this.$api.OpenDoor, data, "GET").then(res => {
                console.log(res)

                // #ifdef MP-ALIPAY
                if (res.code == 200) {
                    uni.navigateTo({
                        url: "/pages/index/successOpen/successOpen?orderId=" + res.result.orderId
                    })
                } else {
                    uni.showModal({
                        title: '开门失败',
                        content: res.message,
                        showCancel: false,
                    });
                }
                // #endif
                // #ifdef MP-WEIXIN
                if (res.code == 200 && res.success) {
                    if (appconf.wx.need_user_confirm) {
                        this.openConfirmPayScore(res.result.orderId, res.result.orderPackage);
                    } else {
                        uni.navigateTo({
                            url: "/pages/index/successOpen/successOpen?orderId=" + res.result.orderId
                        });
                    }
                } else {
                    uni.showModal({
                        title: '开门失败',
                        content: res.message,
                        showCancel: false,
                    });
                }
                // #endif
            })
        },

        // 扫码
        startScanCode: function() {
            uni.scanCode({
                onlyFromCamera: false,
                success: (res) => {
                    this.$util.extractUri(this, res.result)
                    this.openCondition();
                    //this.getPageData();
                    this.isManage();
                },
                complete: (res) => {
                    console.log(res)
                }
            });
        },

        // 分类选择
        classySelect: function(index) {
            this.classyIndex = index;
        },

        // 查询是否上货员
        isManage: function() {
            let data = {
                userId: this.$store.state.userInfo.userId,
                deviceId: this.$store.state.deviceId,
            }
            this.$request(this.$api.IsManage, data, "POST", true, "application/x-www-form-urlencoded").then(res => {
                let data = JSON.parse(res.data)

                if (data && data.courier == "true") {
                    this.$store.state.isManage = true;
                } else {
                    this.$store.state.isManage = false;
                }
            });
        },

        serviceContact: function() {
            uni.makePhoneCall({
                phoneNumber: this.$store.state.userInfo.customerTel || '--', // 电话
            });
        }

    }
}